package pers.burgess.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

import pers.burgess.xml.handler.EnhanceHandler;
import pers.burgess.xml.handler.XmlBuilder;
import pers.burgess.xml.model.Book;
import pers.burgess.xml.util.FileUtil;

/**
 * XML Best Practice
 * 
 * @author Burgess Li
 *
 */
public class App 
{
    public static void main( String[] args )
    {

    	File xmlFile = new File(App.class.getResource("/books.xml").getFile());
    	List<Book> bookList = null;
    	
    	// parse xml file content to book list
    	SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    	try {
    		
			SAXParser parser = saxParserFactory.newSAXParser();
	        EnhanceHandler<Book> handler = new EnhanceHandler<Book>(Book.class);
	        parser.parse(new FileInputStream(xmlFile), handler);
	        bookList = handler.getList();
	        
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    	try {
    		
    		// build xml content from book list
			String xml = XmlBuilder.buildXml(bookList);
			File projectDir = new File(System.getProperty("user.dir"));
			File outFile = new File(projectDir, UUID.randomUUID().toString().replaceAll("-", "") + ".xml");
			// write xml file
			FileUtil.writeToFile(xml, outFile);
			
			System.out.println("write xml file to: " + outFile.getAbsolutePath());
			
		} catch (IOException e) {
			e.printStackTrace();
		}
        
    }
}
